import numpy
import numpy as np


def calculate_intersection(p0: np.ndarray, p1: np.ndarray, r0, r1):
    """
    计算两个圆的交点
    calculate the intersection of two circles
    https://stackoverflow.com/questions/3349125/circle-circle-intersection-points
    :param p0: 圆0的圆心
    :param p1: 圆1的圆心
    :param r0: 圆0的半径
    :param r1: 圆1的半径
    :return: 交点
    """

    # 圆心距离
    # distance between two circles' centers
    d = np.linalg.norm(p0 - p1)
    # 半径之和
    # sum of two circles' radii
    r = r0 + r1

    # 一个圆在另一个圆内，则没有交点
    # if one circle is inside the other, there is no intersection
    if d < np.abs(r0 - r1):
        return None

    # 如果两圆相离，则没有交点
    # if two circles are separate, there is no intersection
    if d > r:
        return None

    # 如果两圆相切，则有一个交点
    # if two circles are tangent, there are one intersections
    if d == r:
        return [p0 + (p1 - p0) * (r0 / r)]

    # 如果两圆相交，则有两个交点
    # if two circles are intersecting, there are two intersections
    a = (r0 * r0 - r1 * r1 + d * d) / (2 * d)

    h0 = np.sqrt(r0 * r0 - a * a)

    p2 = p0 + (p1 - p0) * a / d

    x3 = p2[0] + h0 * (p1[1] - p0[1]) / d
    y3 = p2[1] - h0 * (p1[0] - p0[0]) / d

    x4 = p2[0] - h0 * (p1[1] - p0[1]) / d
    y4 = p2[1] + h0 * (p1[0] - p0[0]) / d

    return np.array([[x3, y3], [x4, y4]])



def calc_radians_between_vector(vec_a, vec_b):
    """
    计算两个向量之间的弧度
    :param vec_a:
    :param vec_b:
    :return:
    """
    # cos_angle = vec_a.dot(vec_b) / (np.linalg.norm(vec_a) * np.linalg.norm(vec_b))
    #
    # sign = 1
    # if np.pi / 2 < cos_angle <= np.pi:
    #     sign = -1
    # return sign * np.arccos(cos_angle)

    return np.arctan2(vec_a[0] * vec_b[1] - vec_a[1] * vec_b[0], vec_a[0] * vec_b[0] + vec_a[1] * vec_b[1])

def rotate(new_radians, org_vector):
    """
    旋转向量
    :param new_radians: 旋转角度
    :param org_vector: 用于旋转的向量
    :return: 旋转后的向量
    """

    # 得到最新的点位
    rot = np.array([
        [np.cos(new_radians), -np.sin(new_radians)],
        [np.sin(new_radians), np.cos(new_radians)]]
    )
    return rot @ org_vector


def calc_slice_count(length):
    """
    https://www.desmos.com/calculator/l15bxp04mh?lang=zh-CN
    横向双曲线
    # a = 0.5
    10 -> 5, 50 -> 12, 100 -> 18
    # a = 0.6
    10 -> 4, 50 -> 10, 100 -> 15
    :param length:
    :return:
    """
    a = 0.6
    s_count = round((np.sqrt(length + (1 / (4 * a * a))) - (1 / (2 * a))) / a)
    return s_count


def round_value(value, round_digit=None):
    if isinstance(value, list) or isinstance(value, tuple):
        if round_digit is None:
            return [round(v) for v in value]

        return [round(v, round_digit) for v in value]

    if round_digit is None:
        return round(value)
    return round(value, round_digit)

if __name__ == '__main__':
    p0 = np.array([0, 0])
    p1 = np.array([4, -3])
    intersection_points = calculate_intersection(p0, p1, 3, 4)
    print(intersection_points)
